package com.lanou3g.HW_0517.view;

import com.lanou3g.HW_0517.pojo.User;
import com.lanou3g.HW_0517.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

@WebServlet(name = "SearchServlet", urlPatterns = "/search")
public class SearchServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        response.setContentType("text/html;charset=utf-8");

        // 获取前端传过来的参数
        String key = request.getParameter("key");

        // 预编译
        String search = "SELECT username, nickname, hobby, gender FROM HW_0517 WHERE username Like ?";
        PreparedStatement statement =
                JDBCUtil.getPreStatement(search);
        // 设置参数
        try {
            statement.setString(1, "%" + key + "%");

            // 获得查询结果
            ResultSet rs = statement.executeQuery();

            // 输出查询结果
            //PrintWriter pw = response.getWriter();

            User user = null;
            ArrayList<User> users = new ArrayList<>();
            while (rs.next()) {
//                String username = rs.getString("username");
//                String nickname = rs.getString("nickname");
//                String hobby = rs.getString("hobby");
//                String gender = rs.getString("gender");
//                pw.println(username);
//                pw.println(nickname);
//                pw.println(hobby);
//                pw.println(gender);
//                pw.println("<br>");
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setNickname(rs.getString("nickname"));
                user.setHobby(rs.getString("hobby"));
                user.setGender(rs.getString("gender"));
                users.add(user);
            }

            request.setAttribute("name", users);
            rs.close();
            JDBCUtil.closeResource(statement);

            // 请求转发到/WEB-INF/result.jsp查看结果
            request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



